from .knowledge import KnowledgePointManager
from .question import QuestionGenerator
from .memory import LearningMemory

class LearningAgent:
    """智能学习代理类"""
    def __init__(self):
        self.knowledge_manager = KnowledgePointManager()
        self.learning_memory = None
        self.current_question = None
        self.selected_kps = []
    
    def initialize_student(self, student_id):
        """初始化学生"""
        self.learning_memory = LearningMemory(student_id)
        self.question_generator = QuestionGenerator(self.knowledge_manager, session_id = student_id)
    
    def set_knowledge_points(self, grade, subject, kp_ids):
        """设置知识点"""
        self.selected_kps = kp_ids
    
    def generate_new_question(self):
        """生成新题目"""
        if not self.selected_kps or not self.learning_memory:
            return None
        
        # 选择一个知识点
        selected_kp = self.question_generator.select_knowledge_point(self.selected_kps, self.learning_memory)
        
        # 生成题目
        self.current_question = self.question_generator.generate_question(selected_kp, self.selected_kps)
        return self.current_question
    
    def check_answer(self, user_answer):
        """检查答案"""
        if not self.current_question:
            return False, "没有当前题目"
        
        # 检查答案是否正确
        is_correct = user_answer == self.current_question["correct_answer"]
        
        # 记录学习情况，包括知识点ID、是否正确和题目内容
        self.learning_memory.record_answer(
            self.current_question["knowledge_point_id"], 
            is_correct, 
            self.current_question["text"]
        )
        
        # 获取题目解释
        explanation = self.current_question["explanation"]
        
        return is_correct, explanation
    
    def get_progress_summary(self):
        """获取学习进度摘要"""
        if not self.learning_memory:
            return "暂无学习记录"
        
        status = self.learning_memory.get_knowledge_point_status()
        if not status:
            return "暂无学习记录"
        
        summary = "学习进度：\n"
        for kp_id, stats in status.items():
            # 获取知识点名称
            kp_name = "未知知识点"
            for grade in self.knowledge_manager.knowledge_points.values():
                for subject in grade.values():
                    for kp in subject:
                        if kp["id"] == kp_id:
                            kp_name = kp["name"]
                            break
            
            summary += f"- {kp_name}：正确率 {stats['accuracy']*100:.1f}% ({stats['total_attempts']}次尝试)\n"
        
        return summary